<template>
  <div class="forum-detail">
    <!-- 帖子内容 -->
    <div class="post-content">
      <div class="post-header">
        <h2 class="post-title">{{ post.title }}</h2>
        <div class="post-meta">
          <span class="author-name">{{ post.username }}</span>
          <span class="post-time">{{ formatTime(post.createTime) }}</span>
          <span class="view-count">浏览 {{ post.viewCount }}</span>
          <span class="comment-count">评论 {{ post.commentCount }}</span>
        </div>
      </div>
      <div class="post-body">
        {{ post.content }}
      </div>
    </div>

    <!-- 评论区 -->
    <div class="comment-section">
      <h3 class="section-title">评论区</h3>
      <div class="comment-form">
        <div v-if="!store.state.user" class="login-tip">
          登录后才能发表评论，
          <el-link type="primary" @click="handleLogin">点击登录</el-link>
        </div>
        <el-input
          v-else
          v-model="commentContent"
          type="textarea"
          :rows="3"
          placeholder="写下你的评论..."
        />
        <el-button
          v-if="store.state.user"
          type="primary"
          @click="handleComment"
          :loading="submitting"
        >
          发表评论
        </el-button>
      </div>
      <!-- 评论列表 -->
      <div v-loading="loading" class="comment-list">
        <div>评论总数: {{ comments.length }}</div>
        <div v-if="comments.length === 0" class="no-comment">
          暂无评论，快来抢沙发吧！
        </div>
        <div v-for="comment in comments" :key="comment.id" class="comment-item">
          <div class="comment-header">
            <!-- 显示完整的评论对象，用于调试 -->
            <pre class="debug-info">{{ JSON.stringify(comment, null, 2) }}</pre>
            <span class="author-name">{{ comment.authorName || comment.username || '未知用户' }}</span>
            <span class="comment-time">{{ formatTime(comment.createTime) }}</span>
          </div>
          <div class="comment-content">{{ comment.content }}</div>
          <!-- 子评论 -->
          <div v-if="comment.children && comment.children.length > 0" class="sub-comments">
            <div v-for="child in comment.children" :key="child.id" class="sub-comment">
              <div class="comment-header">
                <span class="author-name">{{ child.authorName || child.username || '未知用户' }}</span>
                <span v-if="child.parentAuthorName" class="reply-to">
                  回复 <span class="parent-author">{{ child.parentAuthorName || '未知用户' }}</span>
                </span>
                <span class="comment-time">{{ formatTime(child.createTime) }}</span>
              </div>
              <div class="comment-content">{{ child.content }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { formatDateTime } from '@/utils/format'

const store = useStore()
const router = useRouter()
const route = useRoute()
const postId = computed(() => route.params.id)
const post = ref({})
const commentContent = ref('')
const submitting = ref(false)
const comments = ref([])
const loading = ref(false)

// 加载帖子详情
const loadPost = async () => {
  try {
    const res = await request.get(`/api/forum/posts/${postId.value}`)
    post.value = res.data
  } catch (error) {
    console.error('加载帖子详情失败:', error)
    ElMessage.error('加载帖子详情失败')
  }
}

// 加载评论列表
const loadComments = async () => {
  try {
    loading.value = true
    console.log('开始加载评论, postId:', postId.value)
    const res = await request.get(`/api/forum/comments`, {
      params: {
        postId: postId.value,
        page: 1,
        size: 100
      }
    })
    console.log('API响应:', res)
    console.log('评论列表:', res.data)
    console.log('评论数据:', JSON.stringify(res.data.records, null, 2))
    comments.value = res.data.records
    // 检查第一条评论的数据结构
    if (res.data.records.length > 0) {
      console.log('第一条评论:', JSON.stringify(res.data.records[0], null, 2))
    }
    console.log('当前评论列表:', comments.value)
  } catch (error) {
    console.error('加载评论失败:', error)
    ElMessage.error('加载评论失败')
  } finally {
    loading.value = false
  }
}

// 格式化时间
const formatTime = (time) => {
  return formatDateTime(time)
}

const handleLogin = () => {
  router.push({
    path: '/login',
    query: { redirect: route.fullPath }
  })
}

const handleComment = async () => {
  if (!store.state.user) {
    ElMessage.warning('请先登录')
    handleLogin()
    return
  }

  if (!commentContent.value) {
    ElMessage.warning('请输入评论内容')
    return
  }

  try {
    submitting.value = true
    await request.post(`/api/forum/posts/${postId.value}/comments`, {
      content: commentContent.value
    })
    ElMessage.success('评论成功')
    commentContent.value = ''
    await loadComments() // 重新加载评论列表
  } catch (error) {
    console.error('发表评论失败:', error)
    ElMessage.error('发表评论失败')
  } finally {
    submitting.value = false
  }
}

// 页面加载时获取评论列表
onMounted(() => {
  loadPost()
  loadComments()
})
</script>

<style scoped>
.login-tip {
  text-align: center;
  margin: 10px 0;
  color: #666;
}

.author-name {
  font-weight: bold;
  color: #409EFF;
  margin-right: 8px;
}

.reply-to {
  color: #666;
  margin-right: 8px;
}

.parent-author {
  color: #409EFF;
}

.comment-time {
  color: #999;
  font-size: 12px;
}

.comment-list {
  margin-top: 20px;
}

.comment-item {
  margin-bottom: 20px;
  padding: 10px;
  border-bottom: 1px solid #eee;
}

.comment-header {
  margin-bottom: 8px;
}

.comment-content {
  margin: 8px 0;
  color: #333;
}

.sub-comments {
  margin-left: 20px;
  padding-left: 10px;
  border-left: 2px solid #eee;
}

.sub-comment {
  margin-top: 10px;
  padding: 8px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.post-content {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.post-header {
  margin-bottom: 20px;
}

.post-title {
  margin: 0 0 10px;
  font-size: 24px;
  color: #333;
}

.post-meta {
  color: #999;
  font-size: 14px;
}

.post-meta > span {
  margin-right: 15px;
}

.post-body {
  font-size: 16px;
  line-height: 1.6;
  color: #333;
}

.section-title {
  margin: 30px 0 20px;
  font-size: 18px;
  color: #333;
}

.comment-form {
  margin: 20px 0;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
}

.no-comment {
  text-align: center;
  color: #999;
  padding: 30px 0;
}

.debug-info {
  font-size: 12px;
  background: #f5f5f5;
  padding: 8px;
  margin: 4px 0;
  white-space: pre-wrap;
  word-break: break-all;
  display: none; /* 默认隐藏，需要时可以改为 block */
}
</style>
